# -*- coding: utf-8 -*- 
"""
Created by hcx on 2017/10/13 13:01.
@author: 胡超翔
"""
from __future__ import absolute_import
from __future__ import unicode_literals

import logging

from django.http import JsonResponse
from django.views import View

logger = logging.getLogger(__name__)


class AutoCompleteView(View):
    """搜索匹配
    :param
    """
    model = ''
    name = ''

    def get(self, request, *args, **kwargs):
        query = self.get_query()
        model_list = self.model.objects.filter(**self.search_name())
        results = {'query': query, 'suggestions': []}
        for model in model_list:
            model_dir = {'value': model.name, 'data': str(model.id)}
            results['suggestions'].append(model_dir)
            # manages.append(manage_dir)
        # json_manages=json.dumps(manages)
        logger.info(u"ajax自动匹配内容:%s" % results)
        return JsonResponse(results)

    def get_query(self):
        """获取到需要搜索的字词"""
        query = self.request.GET.get('query', '')
        return query

    def search_name(self):
        """模糊查询需要匹配的字段"""
        kwargs = {
            '{}__{}'.format(self.name, 'icontains'): self.get_query()
        }
        return kwargs
